Coursework 1: Image filtering¶
In this coursework you will practice techniques for image filtering. The coursework includes coding questions and written questions. Please read both the text and the code in this notebook to get an idea what you are expected to implement.
What to do?¶
Complete and run the code using
jupyter-laborjupyter-notebookto get the results.Export (File | Save and Export Notebook As...) the notebook as a PDF file, which contains your code, results and answers, and upload the PDF file onto Scientia.
Instead of clicking the Export button, you can also run the following command instead:
jupyter nbconvert coursework_01_solution.ipynb --to pdfIf Jupyter complains about some problems in exporting, it is likely that pandoc (https://pandoc.org/installing.html) or latex is not installed, or their paths have not been included. You can install the relevant libraries and retry. Alternatively, use the Print function of your browser to export the PDF file.
If Jupyter-lab does not work for you at the end (we hope not), you can use Google Colab to write the code and export the PDF file.
Dependencies:¶
You need to install Jupyter-Lab (https://jupyterlab.readthedocs.io/en/stable/getting_started/installation.html) and other libraries used in this coursework, such as by running the command:
pip3 install [package_name]
# Import libaries (provided)
import imageio.v3 as imageio
import numpy as np
import matplotlib.pyplot as plt
import noise
import scipy
import scipy.signal
import math
import time
1. Moving average filter (20 points).¶
Read the provided input image, add noise to the image and design a moving average filter for denoising.
You are expected to design the kernel of the filter and then perform 2D image filtering using the function scipy.signal.convolve2d().
# Read the image (provided)
image = imageio.imread('campus_snow.jpg')
plt.imshow(image, cmap='gray')
plt.gcf().set_size_inches(8, 8)
x = 1
# Corrupt the image with Gaussian noise (provided)
image_noisy = noise.add_noise(image, 'gaussian')
plt.imshow(image_noisy, cmap='gray')
plt.gcf().set_size_inches(8, 8)
# Design the filter h
### Insert your code ###
h = np.ones((3, 3), dtype=float) # 3x3 matrix of 1s
h = h / 9 # 3x3 of 1/9s
# Convolve the corrupted image with h using scipy.signal.convolve2d function
### Insert your code ###
from scipy.signal import convolve2d
image_smoothed = convolve2d(image_noisy, h, mode="full", boundary="fill", fillvalue=0) # does padding on the boundaries, pads with 0s
# Print the filter (provided)
print('Filter h:')
print(h)
# Display the filtering result (provided)
plt.imshow(image_smoothed, cmap='gray')
plt.gcf().set_size_inches(8, 8)
Filter h: [[0.11111111 0.11111111 0.11111111] [0.11111111 0.11111111 0.11111111] [0.11111111 0.11111111 0.11111111]]
1.2 Filter the noisy image with a 11x11 moving average filter.¶
# Design the filter h
### Insert your code ###
h = np.ones((11, 11), dtype=float) / 11 ** 2 # 11x11 of 1/121 s
# Convolve the corrupted image with h using scipy.signal.convolve2d function
### Insert your code ###
image_smoothed = convolve2d(image_noisy, h) # again pads with 0s on boundaries, these values from earlier are default
# Print the filter (provided)
print('Filter h:')
print(h)
# Display the filtering result (provided)
plt.imshow(image_smoothed, cmap='gray')
plt.gcf().set_size_inches(8, 8)
Filter h: [[0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446] [0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446] [0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446] [0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446] [0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446] [0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446] [0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446] [0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446] [0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446] [0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446] [0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446 0.00826446]]
1.3 Comment on the filtering results. How do different kernel sizes influence the filtering results?¶
Insert your answer¶
Increasing the kernel size increases the averaging window we are considering, this measn that a larger nummber of pixels around a central pixel will be taken into the calculation of the central pixel value. In terms of the images created, this results in blurrier images
2. Edge detection (56 points).¶
Perform edge detection using Sobel filtering, as well as Gaussian + Sobel filtering.
2.1 Implement 3x3 Sobel filters and convolve with the noisy image.¶
# Design the filters
### Insert your code ###
sobel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], dtype=np.float64) # h_x
sobel_y = np.rot90(sobel_x, k = 1, axes = (0, 1)) # h_y
# Image filtering
### Insert your code ###
g_x = convolve2d(image_noisy, sobel_x, mode="same", boundary="symm", fillvalue=0) # symm avoids creating edges at the boundaries
g_y = convolve2d(image_noisy, sobel_y, mode="same", boundary="symm", fillvalue=0)
# Calculate the gradient magnitude
### Insert your code ###
# gx_2 = g_x.dot(g_x)
# gy_2 = g_y.dot(g_y)
grad_mag = np.hypot(g_x, g_y)
# Print the filters (provided)
print('sobel_x:')
print(sobel_x)
print('sobel_y:')
print(sobel_y)
# Display the magnitude map (provided)
plt.imshow(grad_mag, cmap='gray')
plt.gcf().set_size_inches(8, 8)
sobel_x: [[-1. 0. 1.] [-2. 0. 2.] [-1. 0. 1.]] sobel_y: [[ 1. 2. 1.] [ 0. 0. 0.] [-1. -2. -1.]]
2.2 Implement a function that generates a 2D Gaussian filter given the parameter $\sigma$.¶
# Design the Gaussian filter
def gaussian_filter_2d(sigma):
# sigma: the parameter sigma in the Gaussian kernel (unit: pixel)
#
# return: a 2D array for the Gaussian kernel
### Insert your code ###
## window size of around ceil (6sigma) ^ 2 ensures a esult is suffidiently
## close to that obtained by the entire Gaussian Distribution
size = math.ceil(6 * sigma)
# Generate the 1D Gaussian kernel
kernel_1D = np.linspace(-(size // 2), size // 2, size)
x, y = np.meshgrid(kernel_1D, kernel_1D)
mult = 1 / (math.sqrt(2 * math.pi) * sigma)
kernel_2D = mult * np.exp(- (x ** 2 + y ** 2) / (2 * (sigma ** 2)))
# Return the 2D Gaussian kernel
return kernel_2D / np.sum(kernel_2D) ## normalise
# Visualise the Gaussian filter when sigma = 5 pixel (provided)
sigma = 5
h = gaussian_filter_2d(sigma)
plt.imshow(h)
<matplotlib.image.AxesImage at 0x7fd8abacc160>
2.3 Perform Gaussian smoothing ($\sigma$ = 5 pixels) and evaluate the computational time for Gaussian smoothing. After that, perform Sobel filtering and show the gradient magintude map.¶
# Construct the Gaussian filter
### Insert your code ###
gauss_filter = gaussian_filter_2d(sigma = 5)
# Perform Gaussian smoothing and count time
### Insert your code ###
start_time = time.time()
image_smoothed = convolve2d(image_noisy, gauss_filter, mode="same", boundary="symm", fillvalue=0)
end_time = time.time()
elapsed_time_2d = end_time - start_time
# Image filtering
### Insert your code ###
g_x = convolve2d(image_smoothed, sobel_x, mode="same", boundary="symm", fillvalue=0)
g_y = convolve2d(image_smoothed, sobel_y, mode="same", boundary="symm", fillvalue=0)
# Calculate the gradient magnitude
### Insert your code ###
grad_mag = np.hypot(g_x, g_y)
print(f"time taken to use 2D gaussian smoothing {elapsed_time_2d}s")
# Display the gradient magnitude map (provided)
plt.imshow(grad_mag, cmap='gray', vmin=0, vmax=100)
plt.gcf().set_size_inches(8, 8)
time taken to use 2D gaussian smoothing 2.2278430461883545s
2.4 Implement a function that generates a 1D Gaussian filter given the parameter $\sigma$. Generate 1D Gaussian filters along x-axis and y-axis respectively.¶
# Design the Gaussian filter
def gaussian_filter_1d(sigma):
# sigma: the parameter sigma in the Gaussian kernel (unit: pixel)
#
# return: a 1D array for the Gaussian kernel
size = math.ceil(6 * sigma)
x = np.linspace(-(size // 2), size // 2, size)
mult = 1 / (math.sqrt(2 * math.pi) * sigma)
kernel_1D = mult * np.exp(- (x ** 2) / (2 * (sigma ** 2)))
### Insert your code ###
return kernel_1D / np.sum(kernel_1D)
# sigma = 5 pixel (provided)
sigma = 5
# The Gaussian filter along x-axis. Its shape is (1, sz).
### Insert your code ###
h_x = np.resize(gaussian_filter_1d(sigma), new_shape=(1, 30))
# The Gaussian filter along y-axis. Its shape is (sz, 1).
### Insert your code ###
h_y = np.resize(h_x, new_shape=(30, 1))
print(h_x.shape)
print(h_y.shape)
# Visualise the filters (provided)
plt.subplot(1, 2, 1)
plt.imshow(h_x)
plt.subplot(1, 2, 2)
plt.imshow(h_y)
(1, 30) (30, 1)
<matplotlib.image.AxesImage at 0x7fd8ab832ef0>
2.6 Perform Gaussian smoothing ($\sigma$ = 5 pixels) using two separable filters and evaluate the computational time for separable Gaussian filtering. After that, perform Sobel filtering, show the gradient magnitude map and check whether it is the same as the previous one without separable filtering.¶
# Perform separable Gaussian smoothing and count time
### Insert your code ###
from scipy.signal import convolve
start_time = time.time()
image_smoothed_x = convolve(image_noisy, h_x, mode="same")
image_smoothed = convolve(image_smoothed_x, h_y, mode="same")
# image_smoothed_x = convolve2d(image_noisy, h_x, mode="same", boundary="symm", fillvalue=0)
# image_smoothed = convolve2d(image_smoothed_x, h_y, mode="same", boundary="symm", fillvalue=0)
end_time = time.time()
elapsed_time_separable = end_time - start_time
# Image filtering
### Insert your code ###
g_x = convolve2d(image_smoothed, sobel_x, mode="same", boundary="symm", fillvalue=0)
g_y = convolve2d(image_smoothed, sobel_y, mode="same", boundary="symm", fillvalue=0)
# Calculate the gradient magnitude
### Insert your code ###
grad_mag2 = np.hypot(g_x, g_y)
# Display the gradient magnitude map (provided)
print(f"time taken to use 2x1D separated gaussian filters {elapsed_time_separable}s")
plt.imshow(grad_mag2, cmap='gray', vmin=0, vmax=100)
plt.gcf().set_size_inches(8, 8)
# Check the difference between the current gradient magnitude map
# and the previous one produced without separable filtering. You
# can report the mean difference between the two.
### Insert your code ###
time taken to use 2x1D separated gaussian filters 0.05274510383605957s
2.7 Comment on the Gaussian + Sobel filtering results and the computational time.¶
Insert your answer¶
It seems the 2D on is quite slow, compared to the separated one, ~2.23s compared to the ~0.05s. This means that the compound 2d filter is around 44 times slower than the other. This time does not include the time it takes for the creation of the filters, but only the convolution time. Therefore, pipelining two 1D filters seems to be the less computationally expensive task.
3. Challenge: Implement 2D image filters using Pytorch (24 points).¶
Pytorch is a machine learning framework that supports filtering and convolution.
The Conv2D operator takes an input array of dimension NxC1xXxY, applies the filter and outputs an array of dimension NxC2xXxY. Here, since we only have one image with one colour channel, we will set N=1, C1=1 and C2=1. You can read the documentation of Conv2D for more detail.
# Import libaries (provided)
import torch
3.1 Expand the dimension of the noisy image into 1x1xXxY and convert it to a Pytorch tensor.¶
# Expand the dimension of the numpy array
### Insert your code ###
expanded_noisy = np.expand_dims(image_noisy, axis = (0, 1)) ## adds extra channels
expanded_noisy.shape
# Convert to a Pytorch tensor using torch.from_numpy
### Insert your code ###
tensor_noisy = torch.from_numpy(expanded_noisy)
tensor_noisy.shape
torch.Size([1, 1, 1280, 1280])
3.2 Create a Pytorch Conv2D filter, set its kernel to be a 2D Gaussian filter and perform filtering.¶
# A 2D Gaussian filter when sigma = 5 pixel (provided)
sigma = 5
h = gaussian_filter_2d(sigma)
from torch.nn.functional import conv2d
# Create the Conv2D filter
gauss_tensor = torch.from_numpy(np.expand_dims(h, axis = (0, 1))) # shape: 1 1 30 30
# gauss_filter = torch.nn.Conv2d(in_channels=2, out_channels=2, kernel_size=30)
# gauss_filter.weight.data = torch.from_numpy(h)
# print(gauss_filter.weight.shape)
print(gauss_tensor.shape)
# Filtering
### Insert your code ###
tensor_smoothed = conv2d(tensor_noisy, gauss_tensor, padding="same")
image_smoothed = tensor_smoothed.squeeze().numpy() ## extract 2D image from 4D tensor
# Display the filtering result (provided)
plt.imshow(image_smoothed, cmap='gray')
plt.gcf().set_size_inches(8, 8)
torch.Size([1, 1, 30, 30])
3.3 Implement Pytorch Conv2D filters to perform Sobel filtering on Gaussian smoothed images, show the gradient magnitude map.¶
# Create Conv2D filters
tensor_sobel_x = torch.from_numpy(np.expand_dims(sobel_x, axis = (0, 1)).astype(np.float64))
tensor_sobel_y = torch.from_numpy(np.expand_dims(sobel_y, axis = (0, 1)).copy().astype(np.float64)) ## fixes the negative stride issue due to rot90
# Perform filtering
### Insert your code ###
tensor_g_x = conv2d(tensor_smoothed, tensor_sobel_x, padding="same")
tensor_g_y = conv2d(tensor_smoothed, tensor_sobel_y, padding="same")
# Calculate the gradient magnitude map
### Insert your code ###
tensor_grad_mag3 = torch.hypot(tensor_g_x, tensor_g_y)
grad_mag3 = tensor_grad_mag3.squeeze().numpy()
# Visualise the gradient magnitude map (provided)
plt.imshow(grad_mag3, cmap='gray', vmin=0, vmax=100)
plt.gcf().set_size_inches(8, 8)